import os

from langchain import hub
from langchain_community.embeddings import DashScopeEmbeddings
from langchain_community.document_loaders import UnstructuredMarkdownLoader
from langchain_community.vectorstores import Chroma
from langchain_core.output_parsers import StrOutputParser
from langchain_core.runnables import RunnablePassthrough
from langchain_community.llms import Tongyi
from langchain_text_splitters import RecursiveCharacterTextSplitter

os.environ["DASHCOPE_API_KEY"]="sk-10920ad0a9d542af96353edd7ab3e613"
markdown_path=r"./README.md"
loader=UnstructuredMarkdownLoader(markdown_path)
data = loader.load()
pass

text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200)
splits = text_splitter.split_documents(data)

embeddings=DashScopeEmbeddings(
    model="text-embedding-v1",dashscope_api_key="sk-10920ad0a9d542af96353edd7ab3e613"
)
vectorstore = Chroma.from_documents(documents=splits, embedding=embeddings)

# Retrieve and generate using the relevant snippets of the blog.
retriever = vectorstore.as_retriever()
prompt = hub.pull("rlm/rag-prompt")
llm = Tongyi(dashscope_api_key="sk-10920ad0a9d542af96353edd7ab3e613")


def format_docs(docs):
    return "\n\n".join(doc.page_content for doc in docs)


rag_chain = (
    {"context": retriever | format_docs, "question": RunnablePassthrough()}
    | prompt
    | llm
    | StrOutputParser()
)
result=rag_chain.invoke("Why YOLOv5")
print(result)
